import 'package:shared_preferences/shared_preferences.dart';

class DataUtils {
  static const String SP_ACCESS_TOKEN = 'access_token';
  static const String SP_REFRESH_TOKEN = 'refresh_token';
  static const String SP_UID = 'uid';
  static const String SP_TOKEN_TYPE = 'token_type';
  static const String SP_EXPIRES_IN = 'expires_in';
  static const String SP_IS_LOGIN = 'is_login';

  // 保存登录信息
  static Future<void> saveLoginInfo(Map<String, dynamic> result) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp
      ..setString(SP_ACCESS_TOKEN, result[SP_ACCESS_TOKEN])
      ..setString(SP_UID, result[SP_REFRESH_TOKEN])
      ..setInt(SP_UID, result[SP_UID])
      ..setString(SP_TOKEN_TYPE, result[SP_TOKEN_TYPE])
      ..setInt(SP_EXPIRES_IN, result[SP_EXPIRES_IN])
      ..setBool(SP_IS_LOGIN, true);
  }

  // 清空登录信息
  static Future<void> clearLoginInfo(Map<String, dynamic> result) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp
      ..setString(SP_ACCESS_TOKEN, '')
      ..setString(SP_UID, '')
      ..setInt(SP_UID, -1)
      ..setString(SP_TOKEN_TYPE, '')
      ..setInt(SP_EXPIRES_IN, -1)
      ..setBool(SP_IS_LOGIN, false);
  }

  // 判断用户是否登录
  static Future<bool> isLogined() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    bool isLogin = sp.getBool(SP_IS_LOGIN);
    return isLogin != null && isLogin;
  }

  // 获取token
  static Future<String> getToken() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp.getString(SP_ACCESS_TOKEN);
  }
}
